package com.mobimagic.lockscreen.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.mobimagic.lockscreen.sdk.LockScreenSDK;
import com.qihoo360.common.utils.Utils;
import com.qihoo360.mobilesafe.lib.appmgr.module.ApplicationEntry;

/**
 * @file AppUtil.java
 *
 * @author liule-ms
 *
 * @date 2014-6-11 下午4:15:19
 *
 * @description
 */
public class AppUtils {
    private static final String TAG = "AppUtils";

    private static final String SCHEME = "package";
    /**
     * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.1及之前版本)
     */
    private static final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";
    /**
     * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.2)
     */
    private static final String APP_PKG_NAME_22 = "pkg";
    /**
     * InstalledAppDetails所在包名
     */
    private static final String APP_DETAILS_PACKAGE_NAME = "com.android.settings";
    /**
     * InstalledAppDetails类名
     */
    private static final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";

    private static final int VERSION_CODES_KITKAT = 19;
    private static final int ICON_SIZE = 48;//dip
    private static Drawable mDefaultDrawable;
    private static DisplayMetrics mDisplaymetrics;
    /**
     * 0代表没初始化，1代表true,2代表false
     */
    private static int noAdData = 0;

    private static void init(Context context) {
        if (mDefaultDrawable == null) {
            mDefaultDrawable = context.getPackageManager().getDefaultActivityIcon();
        }
        if (mDisplaymetrics == null) {
            mDisplaymetrics = new DisplayMetrics();
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(
                    mDisplaymetrics);
        }
    }

    public static Drawable getDefaultDrawable(Context context) {
        AppUtils.init(context);
        return mDefaultDrawable;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    private static int getBitmapSize(Bitmap bitmap) {
        if (bitmap == null) {
            return 0;
        }
        if (Build.VERSION.SDK_INT >= VERSION_CODES_KITKAT) { //API 19
            Class<Bitmap> clazz = Bitmap.class;
            Method method;
            try {
                method = clazz.getMethod("getAllocationByteCount");
                return (Integer) method.invoke(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
            return bitmap.getByteCount();
        }
        return bitmap.getRowBytes() * bitmap.getHeight();//earlier version
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        //先根据宽度进行缩小
        while (width / reqWidth > inSampleSize) {
            inSampleSize++;
        }
        //然后根据高度进行缩小
        while (height / reqHeight > inSampleSize) {
            inSampleSize++;
        }
        return inSampleSize;
    }

    public void getMetrics(Activity context) {
        // 获取屏幕密度（方法1）
        int screenWidth = context.getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
        int screenHeight = context.getWindowManager().getDefaultDisplay().getHeight(); // 屏幕高（像素，如：800p）

        Log.e(TAG + "  getDefaultDisplay", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight);

        // 获取屏幕密度（方法2）
        DisplayMetrics dm = context.getResources().getDisplayMetrics();

        float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
        int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
        float xdpi = dm.xdpi;
        float ydpi = dm.ydpi;

        Log.e(TAG + "  DisplayMetrics", "xdpi=" + xdpi + "; ydpi=" + ydpi);
        Log.e(TAG + "  DisplayMetrics", "density=" + density + "; densityDPI=" + densityDPI);

        screenWidth = dm.widthPixels; // 屏幕宽（像素，如：480px）
        screenHeight = dm.heightPixels; // 屏幕高（像素，如：800px）

        Log.e(TAG + "  DisplayMetrics", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight);

        // 获取屏幕密度（方法3）
        dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);

        density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
        densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
        xdpi = dm.xdpi;
        ydpi = dm.ydpi;

        Log.e(TAG + "  DisplayMetrics 2", "xdpi=" + xdpi + "; ydpi=" + ydpi);
        Log.e(TAG + "  DisplayMetrics 2", "density=" + density + "; densityDPI=" + densityDPI);

        int screenWidthDip = dm.widthPixels; // 屏幕宽（dip，如：320dip）
        int screenHeightDip = dm.heightPixels; // 屏幕宽（dip，如：533dip）

        Log.e(TAG + "  DisplayMetrics 2", "screenWidthDip=" + screenWidthDip + "; screenHeightDip=" + screenHeightDip);

        screenWidth = (int) (dm.widthPixels * density + 0.5f); // 屏幕宽（px，如：480px）
        screenHeight = (int) (dm.heightPixels * density + 0.5f); // 屏幕高（px，如：800px）

        Log.e(TAG + "  DisplayMetrics 2", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight);
    }

    public static int getDimension(Context context, int dimenId) {
        Resources resources = context.getResources();
        return resources.getDimensionPixelSize(dimenId);
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getWidth(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public static int getHeight(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    public static int getStatusBarHeight(Context context) {
        Resources res = context.getResources();
        int result = 0;
        int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = res.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int getTitleBarHeight(Activity activity) {
        int contentTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
        int statusBarHeight = AppUtils.getStatusBarHeight(activity);
        return contentTop - statusBarHeight;
    }

    public static void showSoftInput(Context c, View view) {
        InputMethodManager im = ((InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE));
        im.showSoftInput(view, 0);
    }

    public static void hideSoftInput(Context c, View view) {
        InputMethodManager im = ((InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE));
        im.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static float getDensity() {
        float density = 1;
        try {
            Context context = LockScreenSDK.getInstance().getContext();
            density = context.getResources().getDisplayMetrics().density;
        } catch (Exception e) {
        }
        return density;
    }

    public static float getDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    public static int getRandomNum(int mixNum, int _num) {
        return (int) (Math.random() * _num);
    }

    public static int getProgress(long downloadSize, long totalSize) {
        if (totalSize == 0) {
            return 0;
        } else {
            return (int) (downloadSize * 100 / totalSize);
        }
    }

    public static float getRating(String rate) {
        if (rate != null) {
            if (rate.trim().length() == 2) {
                return Float.valueOf(rate) / 10;
            } else {
                return Float.valueOf(rate);
            }
        }
        return 0;
    }

    public static int[] getLocationOnScreen(View v) {
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        return location;
    }

    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375) {
                c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    public static void setComponentEnabled(Context context, Class<?> cls, boolean enabled) {
        final ComponentName c = new ComponentName(context, cls.getName());
        context.getPackageManager().setComponentEnabledSetting(
                c,
                enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
    }

    public static int getTextToInteger(String text) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        } else if (TextUtils.isDigitsOnly(text)) {
            return Integer.valueOf(text);
        }
        return 0;
    }

    /**
     * 调用系统InstalledAppDetails界面显示已安装应用程序的详细信息。 对于Android 2.3（Api Level
     * 9）以上，使用SDK提供的接口； 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）。
     *
     * @param context
     *
     * @param packageName
     *            应用程序的包名
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void showAppDetails(Context context, String packageName) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        final int apiLevel = Build.VERSION.SDK_INT;
        if (apiLevel >= 9) { // 2.3（ApiLevel 9）以上，使用SDK提供的接口
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts(SCHEME, packageName, null);
            intent.setData(uri);
        } else { // 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
            final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22 : APP_PKG_NAME_21);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName(APP_DETAILS_PACKAGE_NAME, APP_DETAILS_CLASS_NAME);
            intent.putExtra(appPkgName, packageName);
        }
        context.startActivity(intent);
    }

    private static boolean isAppRunning(Context context, String packageName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> processInfos = manager.getRunningAppProcesses();
        boolean isAppRunning = false;
        if (processInfos != null) {
            for (RunningAppProcessInfo info : processInfos) {
                if (info.pkgList != null) {
                    for (String pkg : info.pkgList) {
                        if (TextUtils.equals(packageName, pkg)) {
                            isAppRunning = true;
                            break;
                        }
                    }
                }
            }
        }
        return isAppRunning;
    }

    public static ArrayList<ApplicationEntry> getAllHasLaucherList(PackageManager packageManager) {
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        ArrayList<ApplicationEntry> allHasLaucherLists = new ArrayList<ApplicationEntry>();
        if (packageManager == null) {
            return allHasLaucherLists;
        }
        try {
            ArrayList<String> packNames = new ArrayList<String>();
            List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(mainIntent, 0);
            for (ResolveInfo resolveInfo : resolveInfos) {
                if (resolveInfo != null && resolveInfo.activityInfo != null) {
                    if (!packNames.contains(resolveInfo.activityInfo.applicationInfo.packageName)) {
                        packNames.add(resolveInfo.activityInfo.applicationInfo.packageName);
                        ApplicationEntry entry = new ApplicationEntry(resolveInfo.activityInfo.applicationInfo);
                        allHasLaucherLists.add(entry);
                    }
                }
            }
        } catch (Exception e) {
            //可能会有remote异常
        }
        return allHasLaucherLists;
    }

    /**
     * 判断应用是否被force stop或者disable掉了。是返回true，否则返回false
     *
     * */
    public static boolean isAppForceStoppedOrDisabled(Context context, String packageName) {
        boolean ret = false;
        try {
            //ApplicationInfo.FLAG_STOPPED是API LEVEL 12引入的，所以要加版本区分
            if (Build.VERSION.SDK_INT < 12) {
                ret = AppUtils.isAppRunning(context, packageName);
            } else {
                ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0);
                if (info != null) {
                    if (((info.flags & ApplicationInfo.FLAG_STOPPED) != 0) || info.enabled == false) {
                        ret = true;
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }

    public static boolean isAppForceStoppedOnly(Context context, String packageName) {
        boolean ret = false;
        try {
            //ApplicationInfo.FLAG_STOPPED是API LEVEL 12引入的，所以要加版本区分
            if (Build.VERSION.SDK_INT < 12) {
                ret = AppUtils.isAppRunning(context, packageName);
            } else {
                ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0);
                if (info != null) {
                    if (((info.flags & ApplicationInfo.FLAG_STOPPED) != 0)) {
                        ret = true;
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }

    public static boolean isAtLanucher(Context mContext) {
        ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<String> lanuchers = Utils.getHomeLauncherPackages(mContext);
        boolean isAtLanucher = false;
        if (Build.VERSION.SDK_INT >= 21) {
            List<RunningAppProcessInfo> processInfos = mActivityManager.getRunningAppProcesses();
            if (processInfos != null && !processInfos.isEmpty()) {
                String[] pkgList = processInfos.get(0).pkgList;
                if (pkgList != null && pkgList.length > 0) {
                    isAtLanucher = lanuchers.contains(pkgList[0]);
                }
            }
        } else {
            List<RunningTaskInfo> taskInfos = mActivityManager.getRunningTasks(1);
            if (taskInfos != null && !taskInfos.isEmpty()) {
                isAtLanucher = lanuchers.contains(taskInfos.get(0).topActivity.getPackageName());
            }
        }
        return isAtLanucher;
    }

    //        public static boolean isSecurityFroeground(Context mContext) {
    //            ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    //            boolean isFroeground = false;
    //            if (Build.VERSION.SDK_INT >= 21) {
    //                List<RunningAppProcessInfo> processInfos = mActivityManager.getRunningAppProcesses();
    //                if (processInfos != null && !processInfos.isEmpty()) {
    //                    String[] pkgList = processInfos.get(0).pkgList;
    //                    if (pkgList != null && pkgList.length > 0) {
    //                        isFroeground = AppEnv.PKGNAME.equals((pkgList[0]));
    //                    }
    //                }
    //            } else {
    //                List<RunningTaskInfo> taskInfos = mActivityManager.getRunningTasks(1);
    //                if (taskInfos != null && !taskInfos.isEmpty()) {
    //                    isFroeground = AppEnv.PKGNAME.equals(taskInfos.get(0).topActivity.getPackageName());
    //                }
    //            }
    //            return isFroeground;
    //        }
    //

    /**
     * 无广告数据
     *
     * @param context
     * @return
     */
    public static boolean noAdData(Context context) {
        if (noAdData == 0) {
            if (AppUtils.getDensity(context) <= 1) {
                noAdData = 1;
                return true;
            }
            if (Build.VERSION.SDK_INT <= 10) {
                noAdData = 1;
                return true;
            }
            noAdData = 2;
            return false;
        } else {
            return noAdData == 1;
        }
    }

}
